#import "WorkitemListViewController.h"
#import "QuestetraBPMAppDelegate.h"
#import "WorkitemListCell.h"
#import "WorkitemEntry.h"
#import "WebViewController.h"

@implementation WorkitemListViewController

- (void) refresh {
    NSMutableArray *res = [qbpmClient fetchWorkitems];
    if(res != nil) {
        [workitems release];
        workitems = res;
        [self.tableView reloadData];
    }
    
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return YES;
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = NSLocalizedString(@"My Tasks", @"label.MyTask");
	qbpmClient = [[QuestetraBPMAppDelegate sharedApp] qbpmClient];
	workitems = [[NSArray alloc] init];
}

- (void)viewDidAppear:(BOOL)animated {
	[self refresh];
    [super viewDidAppear:animated];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [workitems count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	// NSLog(@"WorkiteListViewControlle#tableView %d", indexPath.row);
	static NSString *CellIdentifier = @"WorkitemCell";
    WorkitemListCell *cell = (WorkitemListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"WorkitemCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    WorkitemEntry *entry = [workitems objectAtIndex:indexPath.row];
    cell.titleLabel.text = entry.processTitle;
    cell.modelLabel.text = entry.processModelName;
    cell.nodeLabel.text = entry.taskName;
    cell.dateLabel.text = [entry offeredDateString];
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	WebViewController* subViewController = [[WebViewController alloc] initWithNibName:@"WebViewController" bundle:nil];
    WorkitemEntry* workitem = [workitems objectAtIndex: indexPath.row];
	NSString* urlString = [qbpmClient.contextRoot stringByAppendingFormat: @"PE/ProcessInstance/viewPrint?processInstanceId=%d", workitem.processInstanceId];
	subViewController.url = [NSURL URLWithString: urlString];
	[self.navigationController pushViewController:subViewController animated:YES];
	[subViewController release];
	
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}


- (void)dealloc {
    [super dealloc];
}


@end

